package com.jwgf.fault;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.jwgf.common.AppContext;

public class DomFaultParse implements IXmlParse {

	@Override
	public HashMap<Integer, FaultContent> getFaultMapByParseXml(InputStream is)
			throws Exception {
		HashMap<Integer, FaultContent> faultMap;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(is);

		Element root = document.getDocumentElement();

		NodeList nodeList = root.getElementsByTagName("Fault");

		if (nodeList == null || nodeList.getLength() == 0)
			return null;

		faultMap = new HashMap<Integer, FaultContent>();

		for (int i = 0; i < nodeList.getLength(); ++i) {
			Element element = (Element) nodeList.item(i);
			String str = getAttrText(element, "code");
			int key = Integer.parseInt(str, 16);
			String value = getAttrText(element, "value");
			int drawable_id = AppContext
					.getInstance()
					.getResources()
					.getIdentifier(getAttrText(element, "drawable"),
							"drawable",
							AppContext.getInstance().getPackageName());
			String detail = getAttrText(element, "detail");
			faultMap.put(key, new FaultContent(value, detail, drawable_id));
		}
		return faultMap;
	}

	/**
	 * 获得指定元素的子元素中的文本内容
	 */
	public String getAttrText(Element element, String name) {
		NodeList nodeList2 = element.getChildNodes();
		Node node = null;
		for (int i = 0; i < nodeList2.getLength(); i++) {
			node = nodeList2.item(i);
			if (node.getNodeName().equals(name)) {
				return node.getTextContent();
			}
		}
		return null;
	}

}
